/*
 * @Copyright: Citylife 2021
 * @Author: QinYulin
 * @Date: 2020-12-14 12:48:48
 * @Description: PermissionManager
 */
import 'dart:developer';
import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:permission_handler_platform_interface/permission_handler_platform_interface.dart';

class PermissionManager {
  List<Permission> _permissions;
  VoidCallback _callback;

  static PermissionManager _instance;
  static PermissionManager get instance => _getInstance();

  // 工厂模式
  factory PermissionManager() => _getInstance();

  PermissionManager._internal() {
    // 初始化
  }

  static PermissionManager _getInstance() {
    if (_instance == null) {
      _instance = new PermissionManager._internal();
    }
    return _instance;
  }

  Future requestPermissions(
      List<Permission> permissions, VoidCallback callback) async {
    _permissions = permissions;
    _callback = callback;
    if ((defaultTargetPlatform == TargetPlatform.iOS) ||
        (defaultTargetPlatform == TargetPlatform.android)) {
      List<Permission> temp = [];

      for (Permission permissionGroup in _permissions) {
        // 判断权限结果
        PermissionStatus permission = await PermissionHandlerPlatform.instance
            .checkPermissionStatus(permissionGroup);

        if (permission != PermissionStatus.granted) {
          temp.add(permissionGroup);
        }
      }

      if (temp.isEmpty) {
        log("全部权限申请成功");
        _callback.call();
      } else {
        log("必须开启全部权限才能进入主程序~");
        _permissions = temp;
        requestPermission();
      }
    } else {
      _callback.call();
    }
  }

  Future requestPermission() async {
    Map<Permission, PermissionStatus> permissions =
        await PermissionHandlerPlatform.instance
            .requestPermissions(_permissions);
    List<Permission> temp = List.from(_permissions);

    for (Permission permissionGroup in _permissions) {
      if (permissions[permissionGroup] == PermissionStatus.granted) {
        log("权限重新申请成功");
        temp.remove(permissionGroup);
        if (temp.isEmpty) {
          log("全部权限申请成功");
          _callback.call();
        }
      } else {
        bool isSHow = true;
        if (Platform.isAndroid) {
          await PermissionHandlerPlatform.instance
              .shouldShowRequestPermissionRationale(permissionGroup);
        }
        if (isSHow) {
          _permissions = temp;
          requestPermission();
        } else {
          log("当前已被您禁用申请权限，请在设置中手动开启后退出重新进入程序");

          showDialog(
              context: Get.overlayContext,
              builder: (context) {
                return AlertDialog(
                  title: Text('当前已被您禁用申请权限，请在设置中手动开启'),
                  // content: Text('确定前往设置页面吗？'),
                  actions: <Widget>[
                    TextButton(
                      child: Text('取消'),
                      onPressed: () async {
                        exit(0);
                      },
                    ),
                    TextButton(
                      child: Text('确认'),
                      onPressed: () async {
                        PermissionHandlerPlatform.instance.openAppSettings();
                        Navigator.pop(context);
                      },
                    ),
                  ],
                );
              });
          return;
        }
      }
    }
  }
}
